//
//  CourseEvaluateVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/13.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "CourseEvaluateVC.h"
#import "CourseEvaluateView.h"
#import "CourseEvaluateUploadFileTool.h"
#import "CourseEvaluateChildModel.h"
#import "CourseEvaluateThreeGoodModel.h"
#import "CourseEvaluateSelectStudentView.h"

@interface CourseEvaluateVC ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    // scrollView的高度 初始高度670
    IBOutlet NSLayoutConstraint *_ScrollViewConstraint;
    // 三好评价 初始高度176
    IBOutlet NSLayoutConstraint *_ThreeViewConstraint;

    /** 一、作业图表 */
    // 学生账号
    IBOutlet UITextField *_StudentAccount;
    // 科目
    IBOutlet UITextField *_Subject;
    // 图片
    IBOutletCollection(UIButton) NSArray *AudioButtonArr;

    /** 二、作业评价 */
    // 共性问题
    IBOutlet UITextView *_CommonProblem;
    // 共性问题的提示文字
    IBOutlet UILabel *_CommonProblemLabel;
    // 共性音频
    IBOutlet UIButton *_CommonAudio;
    // 共性音频的ID
    NSString *_CommonAudioID;
    // 个性问题
    IBOutlet UITextView *_PersonalProblem;
    // 个性问题的提示文字
    IBOutlet UILabel *_PersonalProblemLabel;
    // 个性音频
    IBOutlet UIButton *_PersonalAudio;
    // 个性音频的ID
    NSString *_PersonalAudioID;

    /** 三、孩子三好评价 */
    // 好成绩View
    IBOutlet UIView *_GoodScore;
    // 好成绩View高度
    IBOutlet NSLayoutConstraint *_GoodScoreConstraint;
    // 好习惯View
    IBOutlet UIView *_GoodHabit;
    // 好习惯View高度
    IBOutlet NSLayoutConstraint *_GoodHabitConstraint;
    // 好素养View
    IBOutlet UIView *_GoodAttainment;
    // 好素养View高度
    IBOutlet NSLayoutConstraint *_GoodAttainmentConstraint;
}
// 操作类
@property (nonatomic, strong) CourseEvaluateUploadFileTool *Tool;
// 图片浏览器
@property (nonatomic, strong) UIImagePickerController *ImagePicker;
// 临时按钮
@property (nonatomic, strong) UIButton *TempButton;
// 图片存储地直,@[@{key:Button}]
@property (nonatomic, strong) NSMutableArray *ImgArr;
// 孩子信息
@property (nonatomic, strong) NSMutableArray <CourseEvaluateChildModel *>*ChildArr;
// 三好问题列表
@property (nonatomic, strong) NSMutableArray <CourseEvaluateThreeGoodModel *>*ThreeGoodArr;
// 三好问题的选项 id-index
@property (nonatomic, strong) NSMutableArray <NSString *>*ThreeGoodSelectArr;
// 选择好学生之后赋值其他报名的ID
@property (nonatomic, copy) NSString *enrollInfoIds;
// 选择好学生的账号
@property (nonatomic, copy) NSString *child_account;
@end

@implementation CourseEvaluateVC


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"课程评价";
    _Subject.text = self.Name;

    // 导航栏右按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:(UIBarButtonItemStyleDone) target:self action:@selector(ClickAdd)];

    // 网络请求
    [self RefreshData];
}

#pragma mark - 网络请求
/**
 获取本页数据
 */
- (void)RefreshData
{
    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"lessonId"  :self.ID,
                             @"action"      :@"getTemplateDetialForCourse"
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        // 创建对象
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 再请求个学生的信息
            [self RefreshChildInfo:^(NSArray<NSDictionary *> *ChildArr) {

                NSDictionary *dict = Obj[@"t"];
                if (![dict isKindOfClass:[NSNull class]])
                {
                    // 好成绩
                    NSArray *comment1Arr = Obj[@"t"][@"comment1"];
                    [comment1Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        // 加入豪华午餐
                        [self.ThreeGoodArr addObject:[CourseEvaluateThreeGoodModel HNObjectValuesForKey:(NSDictionary *)obj]];
                    }];
                    [self ConfigGoodSource];

                    // 好习惯
                    NSArray *comment2Arr = Obj[@"t"][@"comment2"];
                    [comment2Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        // 加入豪华午餐
                        [self.ThreeGoodArr addObject:[CourseEvaluateThreeGoodModel HNObjectValuesForKey:(NSDictionary *)obj]];
                    }];
                    [self ConfigGoodHabit];

                    // 好素养
                    NSArray *comment3Arr = Obj[@"t"][@"comment3"];
                    [comment3Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        // 加入豪华午餐
                        [self.ThreeGoodArr addObject:[CourseEvaluateThreeGoodModel HNObjectValuesForKey:(NSDictionary *)obj]];
                    }];
                }

                [self ConfigGoodAttainment];
                // 孩子列表
                [ChildArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 加豪华午餐
                    [self.ChildArr addObject:[CourseEvaluateChildModel HNObjectValuesForKey:(NSDictionary *)obj]];
                }];
            }];
        }
        else
        {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        [MBProgressHUD showError:NetErr];
    }];
}

/**
 获取学生信息
 */
- (void)RefreshChildInfo:(void(^)(NSArray <NSDictionary *>*))Success
{
    NSDictionary *Params = @{
                             @"lessonId"    :self.ID,
                             @"action"      :@"getCourseRecord2",
                             @"pageNumber"  :@1
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 取模型
            NSArray *Arr = Obj[@"t"][@"dataList"];
            Success (Arr);
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
    }];
}

/**
 添加数据
 */
- (void)RefreshDataForCommitEvaWithaction:(NSString *)action
                                imgFileId:(NSString *)imgFileId
                                 lessonId:(NSString *)lessonId
                                  comment:(NSString *)comment
                                subjectId:(NSString *)subjectId
                                childName:(NSString *)childName
                             commonFileId:(NSNumber *)commonFileId
                            enrollInfoIds:(NSString *)enrollInfoIds
                            commonProblem:(NSString *)commonProblem
                           personalFileId:(NSNumber *)personalFileId
                          personalProblem:(NSString *)personalProblem
{
    [HUD showHUD];
    NSDictionary *Params = @{
                             @"action"          :action?:@"",
                             @"imgFileId"       :imgFileId?:@"",
                             @"lessonId"        :lessonId?:@"",
                             @"comment"         :comment?:@"",
                             @"subjectId"       :subjectId,
                             @"uids"            :childName?:@"",
                             @"commonFileId"    :commonFileId?:@0,
                             @"enrollInfoIds"   :enrollInfoIds,
                             @"commonProblem"   :commonProblem?:@"",
                             @"personalFileId"  :personalFileId?:@0,
                             @"personalProblem" :personalProblem?:@""
                             };
    [NetManager Post:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            [HUD showSuccess:Obj[@"msg"]];
            [self performSelector:@selector(Pop) withObject:nil afterDelay:1.5];
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
    }];
}

#pragma mark - 好成绩、好习惯、好素养
/**
 好成绩
 */
- (void)ConfigGoodSource
{
    [self MgrThreeGoodUI:@1 ThreeGoodView:_GoodScore ViewConstraint:_GoodScoreConstraint];
}

/**
 好习惯
 */
- (void)ConfigGoodHabit
{
    [self MgrThreeGoodUI:@2 ThreeGoodView:_GoodHabit ViewConstraint:_GoodHabitConstraint];
}

/**
 好素养
 */
- (void)ConfigGoodAttainment
{
    [self MgrThreeGoodUI:@3 ThreeGoodView:_GoodAttainment ViewConstraint:_GoodAttainmentConstraint];
}

#pragma mark - 点击事件
/**
 选择学生账号
 */
- (IBAction)OpenStudentAccount:(UIButton *)sender
{
    [self MgrSelectStudentAccount];
}

/**
 选择科目 2017.7.21需求更改，该事件里的所有方法未启用
 */
- (IBAction)OpenSubject:(UIButton *)sender
{
    [self MgrSelectSubject];
}

/**
 单击了图片
 */
- (IBAction)ClickImgButton:(UIButton *)sender
{
    // 处理事件
    [self MgrClickImgButtonAction:sender];
}

/**
 单击了添加
 */
- (void)ClickAdd
{
    [self MgrAdd];
}


#pragma mark - 处理点击事件
/**
 处理单击了图片事件
 */
- (void)MgrClickImgButtonAction:(UIButton *)Button
{
    // 打开选择框
    [self.Tool ShowAlertWithSelect:^(NSInteger Item) {
        // 0相册 1音频 2删除
        if (Item == 0)
        {   // 相册
            [self MgrUploadImg:Button];
        }
        else if (Item == 1)
        {   // 音频
            [self MgrUploadAudio:Button];
        }
        else if (Item == 2)
        {   // 删除
            [self MgrDeleteFile:Button];
        }
    }];
}

/**
 处理图片上传
 */
- (void)MgrUploadImg:(UIButton *)Button
{
    self.TempButton = Button;
    [self presentViewController:self.ImagePicker animated:YES completion:nil];
}

/**
 处理音频上传
 */
- (void)MgrUploadAudio:(UIButton *)Button
{
    self.TempButton = Button;
    // 开始处理音频上传
    [self.Tool UploadAVAudioWithButton:Button Complete:^(NSString *AudioName) {

        AudioName = [AudioName stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
        AudioName = [AudioName stringByReplacingOccurrencesOfString:@"\n" withString:@""];

        if (Button == _CommonAudio)
        {
            // 共性音频
            _CommonAudioID = AudioName;
        }
        else if (Button == _PersonalAudio)
        {
            // 个性音频
            _PersonalAudioID = AudioName;
        }
        else
        {
            [self.ImgArr addObject:@{AudioName:self.TempButton}];
        }
    }];
}

/**
 删除已经上传好的文件
 */
- (void)MgrDeleteFile:(UIButton *)Button
{
    // 临时保存地
    __block NSDictionary *TempDict = nil;
    // 在字典里看下有没有
    [self.ImgArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 提出字典里面的value
        NSArray *ValueArr = [(NSDictionary *)obj allValues];
        // value肯定是button
        UIButton *objButton = (UIButton *)[ValueArr firstObject];
        // 判断一下,如果存放就保存这个字典
        if (Button == objButton)
        {
            // 保存下来
            TempDict = (NSDictionary *)obj;
        }
    }];
    // 检查这个TempDict，有值说明这个button已经有数据了,清除掉
    TempDict ? [self.ImgArr removeObject:TempDict] : nil;
    // 不管理TempDict是否有值，这个button的图片还是要更换的
    [Button setBackgroundImage:[UIImage imageNamed:@"btn_add_sel"] forState:(UIControlStateNormal)];

}

/**
 处理选择学生账号
 */
- (void)MgrSelectStudentAccount
{
    if (self.ChildArr.count == 0)
    {
        [HUD showError:@"暂无学生信息"];
        return;
    }

    // 显示学生的信息
    [CourseEvaluateSelectStudentView CourseEvaluateSelectStudentViewWithTitle:@"请选择您的学生" ChildArr:self.ChildArr SelectRow:^(NSInteger Item) {
        // 取对象
        CourseEvaluateChildModel *Model = self.ChildArr[Item];
        // 赋值
        _StudentAccount.text = [NSString stringWithFormat:@"%@(%@)",Model.child_petName,Model.enrollInfoId];
        self.child_account = [Model.ID stringValue];
        // 报名ID
        self.enrollInfoIds = [Model.enrollInfoId stringValue];
    }];
}

/**
 处理选择科目
 */
- (void)MgrSelectSubject
{
    // 科目
    __block NSArray *SubjectArr = @[@"语文",@"数学",@"英语"];
    // 显示科目
    [CourseEvaluateSelectStudentView CourseEvaluateSelectSubjectViewWithTitle:@"请选择您的科目" SubjectArr:SubjectArr SelectRow:^(NSInteger Item) {
        // 取值
        _Subject.text = SubjectArr[Item];
    }];
}

/**
 处理三好问题的UI
 */
- (void)MgrThreeGoodUI:(NSNumber *)Type ThreeGoodView:(UIView *)ThreeGoodView ViewConstraint:(NSLayoutConstraint *)ViewConstraint
{
    __block NSMutableArray <CourseEvaluateThreeGoodModel *>*Arr = [NSMutableArray array];
    // 循环看看
    [self.ThreeGoodArr enumerateObjectsUsingBlock:^(CourseEvaluateThreeGoodModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 要不要加入豪华午餐
        if ([obj.type isEqualToNumber:Type])
        {
            [Arr addObject:obj];
        }
    }];
    // UI
    [Arr enumerateObjectsUsingBlock:^(CourseEvaluateThreeGoodModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        // 不是相对应的就跳过
        if ([obj.type isEqualToNumber:Type])
        {
            // 好成绩的布局
            CourseEvaluateView *View = [CourseEvaluateView ConfigViewWithTitle:obj.content Y:0 SelectItem:^(NSString *Title, NSInteger Item) {
                // 判断成功后赋值临时str
                __block NSString *TempStr = @"";
                // 循环看看之前有没有加入
                [self.ThreeGoodSelectArr enumerateObjectsUsingBlock:^(NSString * _Nonnull Str, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 取出
                    NSArray *Arr = [Str componentsSeparatedByString:@"-"];
                    // 第一个肯定是ID
                    NSString *Key = [Arr firstObject];
                    // 如果有就停止循环并将这个值放进临时str
                    if ([Key isEqualToString:[obj.ID stringValue]])
                    {
                        TempStr = Str;
                        *stop = YES;
                    }
                    // end
                }];
                // 判断数组里面是否有这个object，有就移除
                [self.ThreeGoodSelectArr containsObject:TempStr] ? [self.ThreeGoodSelectArr removeObject:TempStr]:nil;
                // 把选项保存起来
                [self.ThreeGoodSelectArr addObject:[NSString stringWithFormat:@"%@-%@",[obj.ID stringValue],[@(Item) stringValue]]];
            }];
            [ThreeGoodView addSubview:View];
            // 布局
            [View mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo (ThreeGoodView.mas_top).offset (44*idx);
                make.right.equalTo (ThreeGoodView);
                make.left.equalTo (ThreeGoodView);
                make.height.equalTo (@44);
            }];
            // 高度
            ViewConstraint.constant += 44;
            _ThreeViewConstraint.constant += 44;
            _ScrollViewConstraint.constant += 44;
        }
    }];
}

/**
 处理了添加事件
 */
- (void)MgrAdd
{
    // 图片
    __block NSMutableArray *imgFileIdArr = [NSMutableArray array];
    [self.ImgArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 强转
        NSDictionary *Dict = (NSDictionary *)obj;
        // 强存
        [imgFileIdArr addObject:[[Dict allKeys] firstObject]];
    }];
    // 三好选项
    NSString *comment = [self.ThreeGoodSelectArr componentsJoinedByString:@","];
    // 图片数据
    NSString *imgFileId = [imgFileIdArr componentsJoinedByString:@","];
    // 课程ID
    NSString *lessonId = [self.ID stringValue];
    // 科目
    NSString *subjectId = @"0";
    // 共性图片ID
    NSString *commonFileId = _CommonAudioID;
    // 共性问题
    NSString *commonProblem = _CommonProblem.text;
    // 个性图片ID
    NSString *personalFileId = _PersonalAudioID;
    // 个性问题
    NSString *personalProblem = _PersonalProblem.text;
    // 接口
    NSString *action = @"saveComment";
    // 学生账号
    NSString *childName = self.child_account;
    // 报名ID
    NSString *enrollInfoIds = self.enrollInfoIds;
    BOOL Right = [self.Tool JudgeWithaction:action
                                  imgFileId:imgFileId
                                   lessonId:lessonId
                                  subjectId:subjectId
                                  childName:childName
                               commonFileId:commonFileId
                              enrollInfoIds:(NSString *)enrollInfoIds
                              commonProblem:commonProblem
                             personalFileId:personalFileId
                            personalProblem:personalProblem
                         ThreeGoodSelectArr:self.ThreeGoodSelectArr
                       ThreeGoodSelectIndex:self.ThreeGoodArr.count];
    // 通过检查，提交数据
    if (Right)
    {
        [self RefreshDataForCommitEvaWithaction:action
                                      imgFileId:imgFileId
                                       lessonId:lessonId
                                        comment:comment
                                      subjectId:subjectId
                                      childName:childName
                                   commonFileId:@([commonFileId integerValue])
                                  enrollInfoIds:enrollInfoIds
                                  commonProblem:commonProblem
                                 personalFileId:@([personalFileId integerValue])
                                personalProblem:personalProblem];
    }
}

/**
 返回
 */
- (void)Pop
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - TextView代理
- (void)textViewDidChange:(UITextView *)textView
{
    // 2100共性问题 2101个性问题
    // 共性
    if (textView.tag == 2100)
    {
        _CommonProblemLabel.hidden = textView.text.length > 0 ? YES:NO;
    }
    // 个性
    if (textView.tag == 2101)
    {
        _PersonalProblemLabel.hidden = textView.text.length > 0 ? YES:NO;
    }
}

#pragma mark - 相册代理
//适用获取所有媒体资源，只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    // 如果是图片
    UIImage *Img = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{

        // 上传图片
        [self.Tool UploadImg:Img Button:self.TempButton Complete:^(NSString *ImgName) {

            ImgName = [ImgName stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
            ImgName = [ImgName stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            // 上传成功 ，放入数组
            if (self.TempButton == _CommonAudio)
            {
                // 共性音频
                _CommonAudioID = ImgName;
            }
            else if (self.TempButton == _PersonalAudio)
            {
                // 个性音频
                _PersonalAudioID = ImgName;
            }
            else
            {
                [self.ImgArr addObject:@{ImgName:self.TempButton}];
            }
        }];
    }];
}

#pragma mark - Setter
- (CourseEvaluateUploadFileTool *)Tool
{
    if (!_Tool)
    {
        _Tool = [[CourseEvaluateUploadFileTool alloc] init];
    }
    return _Tool;
}

- (UIImagePickerController *)ImagePicker
{
    if (!_ImagePicker)
    {
        _ImagePicker = [[UIImagePickerController alloc] init];
        _ImagePicker.delegate = self;
        _ImagePicker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _ImagePicker.allowsEditing = YES;
    }
    return _ImagePicker;
}

- (NSMutableArray *)ImgArr
{
    if (!_ImgArr)
    {
        _ImgArr = [NSMutableArray array];
    }
    return _ImgArr;
}

- (NSMutableArray<CourseEvaluateThreeGoodModel *> *)ThreeGoodArr
{
    if (!_ThreeGoodArr)
    {
        _ThreeGoodArr = [NSMutableArray array];
    }
    return _ThreeGoodArr;
}

- (NSMutableArray<CourseEvaluateChildModel *> *)ChildArr
{
    if (!_ChildArr)
    {
        _ChildArr = [NSMutableArray array];
    }
    return _ChildArr;
}

- (NSMutableArray<NSString *> *)ThreeGoodSelectArr
{
    if (!_ThreeGoodSelectArr)
    {
        _ThreeGoodSelectArr = [NSMutableArray array];
    }
    return _ThreeGoodSelectArr;
}
@end
